<!-- 空间的模块 -->
<template>
  <div>
    <div class="right" style="margin-top: 20px">
      <el-form @submit.native.prevent label-width="80px" :inline="true">
        <el-form-item>
          <el-button type="primary" @click="createvisible = true" size="small"
            >创建空间</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <nice-table
      :data="spaceList"
      :showSelection="true"
      :columns="spaceColumns"
      :pagination="spacePagination"
    >
      <el-table-column
        label="操作"
        align="center"
        width="200"
        slot="opreation"
        fixed="right"
      >
        <template slot-scope="scope">
          <!-- <el-button size="small" type="text" @click="applyHandle(scope.row)"
            >报名</el-button
          > -->
          <el-button size="small" type="text" @click="editSpace(scope.row)"
            >配置设备</el-button
          >
        </template>
      </el-table-column>
    </nice-table>
    <el-dialog
      title="创建空间"
      :close-on-click-modal="false"
      :visible.sync="createvisible"
      width="1000px"
      height="700px"
    >
      <el-form
        :model="createSpace"
        ref="form"
        label-width="100px"
        :rules="formRules"
      >
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="空间名称：" prop="roomName">
              <el-input
                v-model="createSpace.roomName"
                placeholder="请输入空间名称"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="行数量：" prop="layoutX">
              <el-input
                v-model="createSpace.layoutX"
                placeholder="请输入行"
                clearable
              >
                <template slot="append">行</template></el-input
              >
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="列数量：" prop="layoutY">
              <el-input
                v-model="createSpace.layoutY"
                placeholder="请输入列"
                clearable
              >
                <template slot="append">列</template></el-input
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="createvisible = false" size="small">取消</el-button>
        <el-button type="primary" @click="adminschoolroomaddFn" size="small"
          >确定</el-button
        >
      </span>
    </el-dialog>
    <el-dialog
      title="配置设备"
      :close-on-click-modal="false"
      :visible.sync="updatavisible"
      width="1000px"
      height="700px"
    >
      <el-form
        @submit.native.prevent
        :model="updataSpace"
        ref="form"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="空间名称：" prop="roomName">
              <el-input
                v-model="updataSpace.roomName"
                placeholder="请输入空间名称"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="行数量：" prop="layoutX">
              <el-input
                v-model="updataSpace.layoutX"
                placeholder="请输入行"
                clearable
                :disabled="updataSpaceArrData[0] ? true : false"
              >
                <template slot="append">行</template></el-input
              >
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="列数量：" prop="layoutY">
              <el-input
                v-model="updataSpace.layoutY"
                placeholder="请输入列"
                clearable
                :disabled="updataSpaceArrData[0] ? true : false"
              >
                <template slot="append">列</template></el-input
              >
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="" prop="layoutY">
              <el-button
                type="primary"
                @click="adminschoolroomupdateFn"
                size="small"
                >确定</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" v-if="updataSpaceArrData[0]">
          <el-col :span="20">
            <el-form-item label="提示：" prop="layoutX">
              当前暂无绑定设备时才可更改行列数量
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="spacebj">
        <div class="spacebj_content cenFlex">
          <div>
            <div class="spacebj_content_y">
              <div class="spacebj_content_x_header"></div>
              <div
                class="spacebj_content_x cenFlex"
                style="border: 0px"
                v-for="(lm, ix) in updataSpace.layoutY"
                :key="'layoutX' + ix"
              >
                第{{ ix + 1 }}列
              </div>
            </div>

            <div
              class="spacebj_content_y"
              v-for="(x, xix) in updataSpaceArr"
              :key="'x' + xix"
            >
              <div class="spacebj_content_x_header">
                第{{ updataSpace.layoutX - xix }}行
              </div>
              <div
                class="spacebj_content_x cenFlex"
                :class="y.id ? 'spacebj_content_x_act' : ''"
                v-for="(y, yix) in x"
                :key="'y' + yix"
                @click="changeSpaceItem(y)"
              >
                {{ y.locationX }}-{{ y.locationY }}
              </div>
            </div>
          </div>
        </div>
        <div class="spacebj_content_jt cenFlex">讲台</div>
      </div>
    </el-dialog>
    <el-dialog
      :title="`${spaceNameItem.locationX}-${spaceNameItem.locationY}绑定设备`"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="spaceNameCreat"
      width="1000px"
      height="700px"
    >
      <el-form @submit.native.prevent ref="form" label-width="130px">
        <el-form-item :label="`绑定设备：`">
          <el-input
            v-model="spaceName"
            placeholder="请输入绑定设备"
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button
          @click="
            () => {
              spaceNameCreat = false
              spaceName = ''
            }
          "
          size="small"
          >取消</el-button
        >
        <el-button type="primary" @click="spaceNameCreatFn('')" size="small"
          >确定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  adminschoolroomadd,
  adminschoolroomupdate,
  adminschoolroomlist,
  adminschoolroomsaveDevice,
  adminschoolroomunBindDevice,
  adminschoolroomdeviceList
} from '@/api/lcmapi.js'
export default {
  props: {
    selectEnums: {
      type: Object,
      default: function () {
        return {}
      }
    },
    basicInfo: {
      type: Object,
      default: function () {
        return {}
      }
    },
    schoolId: ''
  },
  data () {
    return {
      formRules: {
        roomName: [
          { required: true, message: '请输入空间名称', trigger: 'blur' }
        ],
        layoutY: [{ required: true, message: '请输入列', trigger: 'blur' }],
        layoutX: [{ required: true, message: '请输入行', trigger: 'blur' }]
      },
      createvisible: false,
      createSpace: {
        roomName: '',
        layoutX: '',
        layoutY: ''
      },
      updatavisible: false,
      updataSpace: {},
      spaceList: [],
      updataSpaceArr: [],
      updataSpaceArrData: [],
      spaceColumns: [
        {
          label: '空间',
          prop: 'roomName'
        },
        {
          label: '空间布局',
          prop: 'layoutTxt'
        },
        {
          label: '设备数',
          prop: 'deviceCount'
        }
      ],
      spacePagination: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      spaceName: '',
      spaceNameCreat: false,
      spaceNameItem: {}
    }
  },
  // 生命周期 - 创建完成（访问当前this实例）
  created () {},
  // 生命周期 - 挂载完成（访问DOM元素）
  mounted () {
    window.addEventListener('keydown', this.keyDown)
    this.getStudentList()
  },
  beforeDestroy () {
    window.removeEventListener('keydown', this.keyDown)
    this.spaceNameCreat = false
  },
  methods: {
    // 点击
    keyDown (e) {
      if (
        e.key == 'Enter' &&
        this.spaceNameCreat &&
        this.$route.name == 'school-detail'
      ) {
        console.log(this.$route)
        this.spaceNameCreatFn(true)
      }
    },
    // 点击确认创建新的空间
    async spaceNameCreatFn (flag) {
      let item = this.spaceNameItem
      if (!this.spaceName) {
        this.$message.error('请输入设备')
        return
      }
      adminschoolroomsaveDevice({
        roomId: item.roomId,
        serialNo: this.spaceName,
        locationX: item.locationX,
        locationY: item.locationY
      }).then(res => {
        if (res[0]) {
          return
        }
        item.id = item.roomId
        this.spaceNameCreat = false
        this.editSpace({ ...this.updataSpace, ...item }, 'edit')
        if (flag) {
          this.enterFn()
        }
      })
    },
    // 如果是按下回车键执行写入后拉起下一个配置
    enterFn () {
      let { locationX, locationY } = this.spaceNameItem
      let { layoutX, layoutY } = this.updataSpace
      console.log(locationX, locationY, layoutX, layoutY)
      let nx, ny
      if (locationY == layoutY) {
        nx = layoutX - (locationX - 1)
        ny = 0
      } else if (locationY < layoutY && locationX >= 0) {
        nx = layoutX - locationX
        ny = locationY
      } else {
        nx = '-1'
        ny = '-1'
      }
      if (nx == '-1' || ny == '-1') {
        return
      }
      if (this.updataSpaceArr[nx][ny]) {
        this.spaceNameItem = this.$deepcopy(this.updataSpaceArr[nx][ny])
        this.spaceName = ''
        if (this.updataSpaceArr[nx][ny].serialNo) {
          this.enterFn()
        } else {
          this.spaceNameCreat = true
        }
      }
    },

    //   点击开始创建空间
    adminschoolroomaddFn () {
      let param = {
        ...this.createSpace,
        schoolId: this.schoolId
      }
      adminschoolroomadd(param).then(res => {
        if (res[0]) {
          return
        }
        this.$message.success('添加成功')
        this.createvisible = false
        this.getStudentList()
      })
    },
    // 点击更新当前的设备信息
    adminschoolroomupdateFn () {
      let param = {
        ...this.updataSpace,
        schoolId: this.schoolId
      }
      adminschoolroomupdate(param).then(res => {
        if (res[0]) {
          return
        }
        this.$message.success('更新成功')
        this.updatavisible = false
        this.getStudentList()
      })
    },
    // 点击配置信息配置
    editSpace (row, typeName) {
      let updataSpaceArr = []
      adminschoolroomdeviceList({ roomId: row.id }).then(res => {
        if (res[0]) {
          return
        }
        for (let h = 0; h < row.layoutX; h++) {
          for (let l = 0; l < row.layoutY; l++) {
            updataSpaceArr[h] = updataSpaceArr[h] ? updataSpaceArr[h] : []
            updataSpaceArr[h][l] = updataSpaceArr[h][l]
              ? updataSpaceArr[h][l]
              : []
            // 默认初始化当前的列表
            updataSpaceArr[h][l] = {
              id: '', // 设备ID
              roomId: row.id, // 房间ID
              locationX: h + 1, // 设备所在行数
              locationY: l + 1, // 设备所在列数
              serialNo: '', // 设备编号
              type: 1,
              createTime: row.createTime,
              updateTime: row.updateTime
            }
            // 如果存在写入数据
            res[1].data.forEach(item => {
              if (item.locationX == h + 1 && item.locationY == l + 1) {
                updataSpaceArr[h][l] = item
              }
            })
          }
        }
        this.updataSpaceArr = updataSpaceArr.reverse()
        this.updataSpaceArr.splice(1, 0)
        this.updataSpace = this.$deepcopy(row)
        this.updatavisible = true
        this.updataSpaceArrData = res[1].data
        console.log(this.updataSpaceArr)
        if (typeName == 'edit') {
          this.getStudentList()
        }
      })
    },
    // 初始获取列表的接口
    async getStudentList () {
      let res = await adminschoolroomlist({
        schoolId: Number(this.schoolId),
        currPage: this.spacePagination.pageNum,
        pageSize: this.spacePagination.pageSize
      })
      if (res[0]) {
        return
      }
      let data = res[1]
      if (data && data.code === 0) {
        this.spacePagination.total = data.data.totalCount
        data.data.list.forEach(ele => {
          ele.layoutTxt = `${ele.layoutX}行${ele.layoutY}列`
        })
        this.spaceList = data.data.list
      } else {
        this.$message.error(data.msg)
      }
    },
    // 点击绑定或者解绑数据
    changeSpaceItem (item) {
      this.spaceNameItem = this.$deepcopy(item)
      if (item.id) {
        this.spaceNameCreat = false
        this.$confirm(`是否将设备${item.serialNo}解绑`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            adminschoolroomunBindDevice({
              deviceId: item.id
            }).then(res => {
              if (res[0]) {
                return
              }
              this.$message({
                type: 'success',
                message: '解绑成功!'
              })
              item.id = item.roomId
              this.editSpace({ ...this.updataSpace, ...item }, 'edit')
            })
          })
          .catch(() => {})
      } else {
        this.spaceName = ''
        this.spaceNameCreat = true
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.cenFlex {
  display: flex;
  align-items: center;
  justify-content: center;
}
.spacebj {
  width: 100%;
  .spacebj_content_jt {
    width: 100px;
    height: 50px;
    border: 1px #333 solid;
    margin: 10px auto;
  }
  .spacebj_content {
    margin: 0px auto;
    .spacebj_content_y {
      display: flex;
      align-items: center;
      margin-bottom: 10px;
      .spacebj_content_x_header {
        width: 50px;
      }
      .spacebj_content_x {
        border-radius: 30px;
        width: 60px;
        height: 40px;
        border: 1px #333 solid;
        margin-right: 10px;
        cursor: pointer;
        &_act {
          background: #3e83f8;
          border: 1px #3e83f8 solid;
          color: #fff;
        }
        &:nth-last-child(1) {
          margin-right: 0px;
        }
      }
    }
  }
}
</style>
